package org.emet.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.emet.dao.FreezerBoxDao;
import org.emet.dao.FreezerCaseDao;
import org.emet.dao.FreezerDao;
import org.emet.entity.biz.Freezer;
import org.emet.entity.biz.FreezerCase;
import org.emet.entity.biz.FreezerRent;
import org.emet.jee.BusinessException;
import org.emet.jee.core.dao.Page;
import org.emet.service.dto.FreezerBoxCriteria;
import org.emet.service.dto.FreezerBoxDisplayItem;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RemotingDestination
public class FreezerBoxService {
	@Autowired
	private FreezerBoxDao freezerBoxDao;
	@Autowired
	private FreezerCaseDao freezerCaseDao;
	@Autowired
	private FreezerDao freezerDao;

	private static Logger logger = LoggerFactory.getLogger(FreezerBoxService.class);

	public void save(Freezer entity, List<FreezerCase> cases) {
		Transaction tx = freezerCaseDao.getSession().beginTransaction();
		try {
			entity.setCaseCount(cases.size());
			freezerBoxDao.save(entity);

			freezerCaseDao.removeByFreezer(entity.getId());
			freezerCaseDao.getSession().clear();

			for (FreezerCase freezerCase : cases) {
				freezerCase.setFreezerId(entity.getId());
				freezerCaseDao.save(freezerCase);
			}

			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	public List<Freezer> getAll() {
		try {
			return freezerBoxDao.getAll();
		} catch (ObjectNotFoundException e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	public Map<String, Object> get(Long id) {
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			Freezer freezer = freezerBoxDao.findUnique("from Freezer where id=?", id);
			List<Object> caseList = freezerCaseDao.find("from FreezerCase where freezerId = ? order by id asc", id);
			map.put("freezer", freezer);
			map.put("caseList", caseList);
			return map;
		} catch (ObjectNotFoundException e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	public List<FreezerCase> findCases(Long freezerId) {
		try {
			return freezerCaseDao.find("from FreezerCase where freezerId = ? order by id asc", freezerId);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	public void del(Long... ids) {
		for (Long id : ids) {
			if (notExist(id)) {
				continue;
			}
			try {
				freezerBoxDao.delete(id);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				throw new BusinessException("发生异常!");
			}
		}
	}

	private boolean notExist(Long id) {
		return get(id) == null;
	}

	public Page<FreezerBoxDisplayItem> search(Page<Freezer> page, FreezerBoxCriteria criteria) {
		try {
			freezerBoxDao.search(page, criteria);
			List<Freezer> result = page.getResult();
			Page<FreezerBoxDisplayItem> resultPage = new Page<FreezerBoxDisplayItem>();
			Date now = new Date();
			for (Freezer freezer : result) {
				FreezerBoxDisplayItem item = new FreezerBoxDisplayItem();
				item.setId(freezer.getId());
				item.setName(freezer.getName());
				item.setRemark(freezer.getRemark());
				item.setStatus(freezer.getStatus());

				int busyCount = 0;
				List<FreezerRent> countBusy = freezerDao.findBusy(freezer.getId());
				for (FreezerRent freezerRent : countBusy) {
					if (freezerRent.getEndDate() != null) {
						if (now.before(freezerRent.getEndDate())) {
							busyCount++;
						}
					} else if (now.before(freezerRent.getExpectEndDate())) {
						busyCount++;
					}
				}
				item.setIdleCount(freezer.getCaseCount() - busyCount);
				resultPage.getResult().add(item);
			}
			resultPage.setAutoCount(page.isAutoCount());
			resultPage.setOrder(page.getOrder());
			resultPage.setOrderBy(page.getOrderBy());
			resultPage.setPageNo(page.getPageNo());
			resultPage.setPageSize(page.getPageSize());
			resultPage.setTotalCount(page.getTotalCount());

			return resultPage;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}
}
